from django.contrib.auth.backends import  ModelBackend
import re
from  .models import User

def jwt_response_payload_handler(token, user=None, request=None):
    '''
       重新jwt 返回响应内容

    :param token:
    :param user:
    :param request:
    :return:
    '''
    print(request.user)
    # save_login_log(request=request)

    return {
        'token': token,
        'username':user.username,
        'user_id':user.id
    }
def get_user_by_account(account):
    '''
    通过输入账号/手机号 获取用户对象
    :param account: 账号/手机号
    :return: 用户对象
    '''
    try:

        if re.match('^1[3-9]\d{9}$',account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user
class UsernameMobileAuthBackend(ModelBackend):
    '''
    重新后端 用户名或手机号认证
    '''
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_account(username)
        if user and user.check_password(password):
            return user